#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2023/11/2 13:31
# file: web_demo.py
# author: Yingxiao Zhang

import json
import gradio as gr
import numpy as np
import soundfile as sf
from rapid_paraformer import RapidParaformer
import time

config_path = "/opt/RapidASR-main/python/resources_en/config.yaml"

paraformer = RapidParaformer(config_path, lang="en")

def recognition(audio):
    sr, y = audio
    assert sr in [48000, 16000]
    if sr == 48000:  # Optional resample to 16000
        y = (y / max(np.max(y), 1) * 32767)[::3].astype("int16")
    sf.write('/opt/RapidASR-main/python/output.wav', y, 16000)
    start = time.time()
    result = paraformer(['/opt/RapidASR-main/python/output.wav'])
    print("time elapsed ", time.time()-start, "s")
    print(result)
    return str(result)

text = "Speech Recognition in WeNet | 基于 WeNet 的语音识别"
gr.Interface(recognition, inputs="mic", outputs="text",
             description=text).launch(share=True,
                inbrowser=True,
                server_name="0.0.0.0",
                server_port=7860)